package com.example.book_libapp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.database.library.DatabaseHandler;
import com.example.database.library.UserFunctions;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class Login extends Activity {

	private EditText inputEmail;
	private EditText inputPass;
	private Button btnLogin;
	private Button btnregister;
	private Button btnpasswordforg;
	private TextView loginErrorMsg;
	private static String api_key = "nmc-android";

	// JSON Response node names
	private static String KEY_STAT = "stat";
	// private static String KEY_UID = "uid";
	private static String KEY_NAME = "name";
	private static String KEY_TOKEN = "token";
	private static String KEY_USER = "user";
	private static String RegisterURL = "http://bookstore-sf14.l:8080/api/"
			+ api_key + "/auth/signup.json";
	// private static String KEY_CREATED_AT = "created_at";
	CheckConnectServer checkserver;

	public void onSearch(View v) {
		onSearchRequested();
	}

	public void onHome(View v) {
		return2Home(this);
	}

	public void return2Home(Context context) {
		final Intent intent = new Intent(context, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		context.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_xml);
		inputEmail = (EditText) findViewById(R.id.InputEmail);
		inputPass = (EditText) findViewById(R.id.InputPass);
		btnLogin = (Button) findViewById(R.id.BtnLog);
		btnregister = (Button) findViewById(R.id.RegisterLogin);
		btnpasswordforg = (Button) findViewById(R.id.ForgotPass);
		loginErrorMsg = (TextView) findViewById(R.id.login_error);

		checkserver = new CheckConnectServer();

		btnLogin.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				String username = inputEmail.getText().toString();
				String password = inputPass.getText().toString();
				CheckInputValue Checkvalue = new CheckInputValue();
				loginErrorMsg.setText("");
				CheckInternetAcces checkaccess = new CheckInternetAcces(
						Login.this);
				if (checkaccess.isOnline(Login.this)) {
					if (checkserver.isConnectedToServer(RegisterURL, 3000)) {
						if (Checkvalue.loginUsername(username)) {
							if (Checkvalue.loginPassword(password)) {
								UserFunctions userFunction = new UserFunctions();
								JSONObject json = userFunction.loginUser(
										username, password);

								try {

									if (json.getString(KEY_STAT).toString()
											.equals("ok")) {

										DatabaseHandler db = new DatabaseHandler(
												getApplicationContext());

										JSONObject json_user = json
												.getJSONObject(KEY_USER);

										db.addUser(
												json_user.getString(KEY_NAME),
												json_user.getString(KEY_TOKEN));

										Intent dashboard = new Intent(
												getApplicationContext(),
												MainActivity.class);

										dashboard
												.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(dashboard);

										finish();
									} else {
										// Error in login
										loginErrorMsg
												.setText(R.string.login_button_error1);
									}

								} catch (JSONException e) {
									e.printStackTrace();
								}
							} else {
								loginErrorMsg
										.setText(R.string.login_button_error3);
							}
						} else {
							loginErrorMsg.setText(R.string.login_button_error2);
						}
					} else {
						loginErrorMsg.setText(""); // Server connect
						String msj = getResources().getString(
								R.string.servererror);
						Toast.makeText(getApplicationContext(), msj,
								Toast.LENGTH_LONG).show();
					}
				} else {
					loginErrorMsg.setText(""); // internet connect
					String msj = getResources().getString(
							R.string.internetrerror);
					Toast.makeText(getApplicationContext(), msj,
							Toast.LENGTH_LONG).show();
				}

				// } catch (Exception e) {
				// e.printStackTrace();
				// }
			}
		});

		// Register button Click Event
		btnregister.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), Register.class);
				startActivity(i);
			}
		});
		btnpasswordforg.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(getApplicationContext(), Passforg.class);
				startActivity(i);
			}
		});

	}
}
